package com.walkline.screen;

import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.Vector;

import javax.microedition.io.HttpConnection;

import net.rim.device.api.i18n.DateFormat;
import net.rim.device.api.i18n.SimpleDateFormat;
import net.rim.device.api.io.IOUtilities;
import net.rim.device.api.io.http.HttpProtocolConstants;
import net.rim.device.api.io.transport.ConnectionDescriptor;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Characters;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.FontFamily;
import net.rim.device.api.ui.FontManager;
import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.Ui;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.Menu;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.menu.SubMenu;
import net.rim.device.api.ui.picker.DateTimePicker;
import net.rim.device.api.util.StringProvider;

import com.walkline.app.MomentAppConfig;
import com.walkline.moment.MomentSDK;
import com.walkline.moment.inf.DailyStories;
import com.walkline.moment.inf.Story;
import com.walkline.util.Enumerations.RefreshActions;
import com.walkline.util.Function;
import com.walkline.util.network.MyConnectionFactory;
import com.walkline.util.network.WorkQueue;
import com.walkline.util.ui.ForegroundManager;
import com.walkline.util.ui.ListStyleButtonField;
import com.walkline.util.ui.ListStyleButtonSet;

public class MomentScreen extends MainScreen
{
	private MomentSDK _moment = MomentSDK.getInstance();
	private WorkQueue _queue = new WorkQueue(3);

	private ForegroundManager _foreground = new ForegroundManager(0);
	private ListStyleButtonField _item;
	private ListStyleButtonSet _dailyStoriesSet = new ListStyleButtonSet();

	private Calendar _currentDate = Calendar.getInstance();
	private SimpleDateFormat STORY_DATEFORMAT = MomentAppConfig.STORY_DATEFORMAT;

    public MomentScreen()
    {
        super (NO_VERTICAL_SCROLL | USE_ALL_HEIGHT | NO_SYSTEM_MENU_ITEMS);

		try {
			FontFamily family = FontFamily.forName("BBGlobal Sans");
			Font appFont = family.getFont(Font.PLAIN, 8, Ui.UNITS_pt);
			FontManager.getInstance().setApplicationFont(appFont);
		} catch (ClassNotFoundException e) {}

        setTitle(MomentAppConfig.APP_TITLE);
        setDefaultClose(false);

        add(_foreground);

        UiApplication.getUiApplication().invokeLater(new Runnable()
        {
			public void run() {getCurrentStories();}
		});
    }

    private void getStories(final String date)
    {
    	UiApplication.getUiApplication().invokeLater(new Runnable()
    	{
			public void run()
			{
		    	DailyStories dailyStories;
				RefreshStoriesScreen popupScreen = new RefreshStoriesScreen(_moment, date, RefreshActions.DAILYSTORIES);
				UiApplication.getUiApplication().pushModalScreen(popupScreen);

				dailyStories = popupScreen.getDailyStories();

				if (popupScreen != null) {popupScreen = null;}
				if (dailyStories != null)
				{
					refreshDailyStories(dailyStories);
					setTitle(MomentAppConfig.APP_TITLE + " - " + dailyStories.getDate());
				}
			}
		});
    }

    private void refreshDailyStories(DailyStories dailyStories)
    {
    	if (_dailyStoriesSet.getManager() == null) {_foreground.add(_dailyStoriesSet);}
		if (_dailyStoriesSet.getFieldCount() > 0) {_dailyStoriesSet.deleteAll();}

		Vector storiesVector = dailyStories.getStories();
		Story story;

		for (int i=0; i<storiesVector.size(); i++)
		{
			story = (Story) storiesVector.elementAt(i);
			if (story != null)
			{
				_item = new ListStyleButtonField(story);
				_item.setChangeListener(new FieldChangeListener()
				{
					public void fieldChanged(Field field, int context)
					{
						if (context != FieldChangeListener.PROGRAMMATIC) {showStoryDetailScreen();}
					}
				});

				_dailyStoriesSet.add(_item);
			}
		}

		if (_dailyStoriesSet.getFieldCount() > 0)
		{
			UiApplication.getUiApplication().invokeLater(new Runnable()
			{
				public void run() {refreshDailyListIcons();}
			});
		}
    }

    private void refreshDailyListIcons()
    {
		ListStyleButtonField item;

		_queue.removeAll();

		for (int i=0; i<_dailyStoriesSet.getFieldCount(); i++)
		{
			Field object = _dailyStoriesSet.getField(i);

			if (object instanceof ListStyleButtonField)
			{
				item = (ListStyleButtonField) object;
				//_queue.execute(new DownloadImages(item));
			}
		}
    }

    private void showStoryDetailScreen()
    {
    	ListStyleButtonField item = (ListStyleButtonField) _dailyStoriesSet.getFieldWithFocus();

    	UiApplication.getUiApplication().pushScreen(new StoryDetailsScreen(_moment, item.getUrl()));
    }

    private void getBeforeStories()
    {
    	Calendar calendar = Calendar.getInstance();
    	calendar.setTime(new Date(calendar.getTime().getTime() - MomentAppConfig.ONE_DAY));

    	DateTimePicker dtPicker = DateTimePicker.createInstance(calendar, "yyyy-MM-dd", null);
    	dtPicker.setMaximumDate(calendar);

    	calendar.set(Calendar.YEAR, 2013);
    	calendar.set(Calendar.MONTH, 5 - 1);
    	calendar.set(Calendar.DAY_OF_MONTH, 19);
    	dtPicker.setMinimumDate(calendar);

    	if (dtPicker.doModal(DateFormat.DATE_FIELD))
    	{
    		_currentDate = dtPicker.getDateTime();
    		_currentDate.set(Calendar.DAY_OF_MONTH, _currentDate.get(Calendar.DAY_OF_MONTH) + 1);

    		getStories(STORY_DATEFORMAT.formatLocal(dtPicker.getDateTime().getTime().getTime() + MomentAppConfig.ONE_DAY));	
    	}
    }

    private void getCurrentStories()
    {
    	_currentDate = Calendar.getInstance();
		_currentDate.set(Calendar.DAY_OF_MONTH, _currentDate.get(Calendar.DAY_OF_MONTH) + 1);
		getStories(null);
    }

    private void getNextStories()
    {
    	_currentDate.set(Calendar.DAY_OF_MONTH, _currentDate.get(Calendar.DAY_OF_MONTH) + 1);

    	if (STORY_DATEFORMAT.formatLocal(_currentDate.getTime().getTime()).equalsIgnoreCase(STORY_DATEFORMAT.formatLocal(Calendar.getInstance().getTime().getTime() + MomentAppConfig.ONE_DAY * 2)))
    	{
    		Function.errorDialog("这是最新的内容，不要再向后翻了！");
    		_currentDate.set(Calendar.DAY_OF_MONTH, _currentDate.get(Calendar.DAY_OF_MONTH) - 1);
    	} else if (STORY_DATEFORMAT.formatLocal(_currentDate.getTime().getTime()).equalsIgnoreCase(STORY_DATEFORMAT.formatLocal(Calendar.getInstance().getTime().getTime() + MomentAppConfig.ONE_DAY))) {
    		getCurrentStories();
    	} else {
    		getStories(STORY_DATEFORMAT.formatLocal(_currentDate.getTime().getTime()));
    	}
    }

    private void getPrevStories()
    {
    	_currentDate.set(Calendar.DAY_OF_MONTH, _currentDate.get(Calendar.DAY_OF_MONTH) - 1);

    	if (STORY_DATEFORMAT.formatLocal(_currentDate.getTime().getTime()).equalsIgnoreCase("20130519"))
    	{
    		Function.errorDialog("这是第一期的内容，不要再向前翻了！");
    		_currentDate.set(Calendar.DAY_OF_MONTH, _currentDate.get(Calendar.DAY_OF_MONTH) + 1);
    	} else {
    		getStories(STORY_DATEFORMAT.formatLocal(_currentDate.getTime().getTime()));
    	}
    }

    private void showExitDialog()
    {
		String[] yesno = {"是 (Y\u0332)", "否 (N\u0332)"};
		Dialog showDialog = new Dialog("确认退出《一刻》？", yesno, null, 0, Bitmap.getPredefinedBitmap(Bitmap.QUESTION), USE_ALL_WIDTH);

		showDialog.doModal();
		if (showDialog.getSelectedValue() == 0) {System.exit(0);}
    }

    private void showAboutScreen()
    {
    	UiApplication.getUiApplication().pushScreen(new AboutScreen());
    }

    protected boolean keyChar(char key, int status, int time)
    {
    	switch (key)
    	{
			case Characters.LATIN_CAPITAL_LETTER_L:
			case Characters.LATIN_SMALL_LETTER_L:
				getCurrentStories();
				return true;
			case Characters.LATIN_CAPITAL_LETTER_T:
			case Characters.LATIN_SMALL_LETTER_T:
				if (_dailyStoriesSet.getFieldCount() > 0) {_dailyStoriesSet.getField(0).setFocus();}
				return true;
			case Characters.LATIN_CAPITAL_LETTER_B:
			case Characters.LATIN_SMALL_LETTER_B:
				if (_dailyStoriesSet.getFieldCount() > 0) {_dailyStoriesSet.getField(_dailyStoriesSet.getFieldCount()-1).setFocus();}
				return true;
			case Characters.LATIN_CAPITAL_LETTER_N:
			case Characters.LATIN_SMALL_LETTER_N:
				getNextStories();
				return true;
			case Characters.LATIN_CAPITAL_LETTER_P:
			case Characters.LATIN_SMALL_LETTER_P:
				getPrevStories();
				return true;
			case Characters.LATIN_CAPITAL_LETTER_A:
			case Characters.LATIN_SMALL_LETTER_A:
				showAboutScreen();
				return true;
			case Characters.LATIN_CAPITAL_LETTER_C:
			case Characters.LATIN_SMALL_LETTER_C:
				getBeforeStories();
				return true;
			case Characters.LATIN_CAPITAL_LETTER_Q:
			case Characters.LATIN_SMALL_LETTER_Q:
				showExitDialog();
				return true;
		}

    	return super.keyChar(key, status, time);
    }

    MenuItem menuLatestStories = new MenuItem(new StringProvider("今日一刻(L\u0332)"), 100, 10)
    {
    	public void run() {getCurrentStories();}
    };

    MenuItem menuBeforeStoriesSelector = new MenuItem(new StringProvider("指定日期(C\u0332)"), 200, 10)
    {
    	public void run() {getBeforeStories();}
    };

    MenuItem menuBeforeStoriesPrev = new MenuItem(new StringProvider("上一期(P\u0332)"), 200, 20)
    {
    	public void run() {getPrevStories();}
    };

    MenuItem menuBeforeStoriesNext = new MenuItem(new StringProvider("下一期(N\u0332)"), 200, 30)
    {
    	public void run() {getNextStories();}
    };

    MenuItem menuAbout = new MenuItem(new StringProvider("关于(A\u0332)"), 100, 30)
    {
    	public void run() {showAboutScreen();}
    };

    MenuItem menuQuit = new MenuItem(new StringProvider("退出(Q\u0332)"), 100, 40)
    {
    	public void run() {showExitDialog();}
    };

    protected void makeMenu(Menu menu, int instance)
    {
    	SubMenu menuBeforeStories = new SubMenu(null, "往期内容", 100, 20);
    	menuBeforeStories.add(menuBeforeStoriesSelector);
    	menuBeforeStories.addSeparator();
    	menuBeforeStories.add(menuBeforeStoriesPrev);
    	menuBeforeStories.add(menuBeforeStoriesNext);

    	menu.add(menuLatestStories);
    	menu.addSeparator();
    	menu.add(menuBeforeStories);
    	menu.addSeparator();
    	menu.add(menuAbout);
    	menu.addSeparator();
    	menu.add(menuQuit);

    	super.makeMenu(menu, instance);
    };

    protected boolean onSavePrompt() {return true;}

    public boolean onClose()
    {
    	UiApplication.getUiApplication().requestBackground();

    	return true;
    }
}